<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head th:replace="_fragment::head('发动态')">
<!--    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">-->
<!--    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">-->
<!--    <meta name="apple-mobile-web-app-status-bar-style" content="black">-->
<!--    <meta name="apple-mobile-web-app-capable" content="yes">-->
<!--    <meta name="format-detection" content="telephone=no">-->
<!--    &lt;!&ndash; 设置默认webkit引擎 &ndash;&gt;-->
<!--    <meta name="renderer" content="webkit">-->
    <meta charset="UTF-8">
    <title>发动态</title>
    <link href="../static/layui/layui.css" rel="stylesheet">
    <link href="../static/css/myui.css" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="../static/extend/inputTags.css"/>

</head>
<style>
    textarea {
        resize: none!important;
        scrollbar-width: none !important;
    }
    .myui-upload-image-container {
        width: 90px;
        height: 90px;
        border-style: dashed;
        border-color: #c0c0c0;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 10px;
    }
    .myui-upload-image-container:hover .myui-upload-image-delete-btn {
        display: block;
    }
    .myui-upload-image-container:hover {
        background-color: #eceaea;
    }
    .myui-upload-image-delete-btn {
        width: 105%;
        height: 25%;
        position: absolute;
        bottom: -5px;
        text-align: center;
        background-color: #605f5f;
        opacity: 50%;
        display: none;
    }
</style>
<body>
    <ul class="layui-nav" th:replace="_fragment::navigate(${user}, 0)">
        <li class="layui-nav-item">
            <a href="">带徽章<span class="layui-badge">9</span></a>
        </li>
        <li class="layui-nav-item">
            <a href="">小圆点<span class="layui-badge-dot"></span></a>
        </li>
        <li class="layui-nav-item" lay-unselect>
            <a href="javascript:;">
                <img src="https://unpkg.com/outeres@0.0.10/demo/avatar/1.jpg" class="layui-nav-img">
            </a>
            <dl class="layui-nav-child">
                <dd><a href="javascript:">子级菜单</a></dd>
                <dd><a href="javascript:">横线隔断</a></dd>
                <hr>
                <dd style="text-align: center;"><a href="">退出</a></dd>
            </dl>
        </li>
    </ul>
    <div class="layui-container" style="margin-top: 15px">
        <div class="layui-card" style="padding: 20px">
            <div class="layui-row layui-font-30" style="font-weight: bold">
                发动态
            </div>
            <div class="layui-row" style="display: flex;margin-top: 20px" id="topics-container">
                <div class="layui-font-14 myui-topic-selections" th:id="${'topic-' + topic.id}" th:onclick="|selectTopic('${topic.id}')|" th:each="topic : ${topics}">[[${topic.name}]]</div>
<!--                <div class="layui-font-14 myui-topic-selections">交流</div>-->
<!--                <div class="layui-font-14 myui-topic-selections">交流</div>-->
<!--                <div class="layui-font-14 myui-topic-selections">交流</div>-->
<!--                <div class="layui-font-14 myui-topic-selections">交流</div>-->
            </div>
            <div class="layui-row" style="margin-top: 20px">
                <div class="layui-row" style="display: flex;position: relative;align-items:center;border-color: #dadada;border-style: solid; border-width: 1px 1px 0 1px;height: 45px;border-top-left-radius: 2px;border-top-right-radius: 2px">
                    <div type="button" style="margin-left: 20px" id="image-button">
                        <i class="layui-icon layui-icon-picture layui-font-26 myui-font-color-deep-gray"></i>
                    </div>
                    <div class="myui-font-color-gray" style="position: absolute;right: 20px">
                        <span id="words-number">0</span><span>&nbsp;/&nbsp;5000</span>
                    </div>
                </div>
                <div class="layui-row">
                    <textarea id="input-text" style="background-color: #f6f6f6;border-bottom: 0" maxlength="5000" placeholder="请输入内容" class="layui-textarea myui-textarea"></textarea>
                </div>
                <div id="upload-container" class="layui-row" style="display: none;background-color: #f6f6f6;border-color: #dadada;border-style: solid; border-width: 0 1px 1px 1px;border-bottom-left-radius: 2px;border-bottom-right-radius: 2px;padding: 20px">
                    <div style="display: flex" id="view-div">
                        <div style="display: flex;">
                            <div class="myui-upload-image-container" style="position: relative">
                                <div class="myui-upload-image-delete-btn">
                                    <i class="layui-icon layui-icon-delete" style="font-size: 18px;"></i>
                                </div>
                                <img style="width: 105%;height: 105%" src="https://unpkg.com/outeres@0.0.10/demo/avatar/1.jpg">
                            </div>
                        </div>

                        <div style="display: flex;">
                            <div class="myui-upload-image-container" style="position: relative">
                                <div class="myui-upload-image-delete-btn">
                                    <i class="layui-icon layui-icon-delete" style="font-size: 18px;"></i>
                                </div>
                                <img style="width: 105%;height: 105%" src="https://unpkg.com/outeres@0.0.10/demo/avatar/1.jpg">
                            </div>
                        </div>
                    </div>


                    <input type="file" style="display: none" id="file-input" multiple accept="image/*">
                    <div class="myui-upload-image-container" onclick="selectImage()">
                        <i class="layui-icon layui-icon-add-1" style="font-size: 30px;color: #5FB878;"></i>
                    </div>
                </div>
            </div>


            <div class="layui-row" style="margin-top: 15px;position: relative">
                <div class="layui-input-block tags" style="display: flex">
                    <div id="tag-div"></div>
                    <input class="layui-input" type="text" id="tag-input" placeholder="回车生成标签" autocomplete="off"/>
                </div>
                <div class="myui-tag-select" style="position: absolute" id="tag-select">
                    <section id="tag-select-div">
<!--                        <div class="myui-font-color-gray myui-tag-option" onclick="addTag('1')">-->
<!--                            <span>1</span>-->
<!--                            <div style="position: absolute;right: 20px">热度&nbsp;<span>21</span></div>-->
<!--                        </div>-->
                    </section>
                </div>
            </div>

            <div class="layui-row" style="margin-top: 15px">
                <button type="button" class="layui-btn" id="post-btn">发布动态</button>
            </div>
        </div>
    </div>

    <div class="layui-row" style="margin-top: 30px;margin-bottom: 20px;text-align: center;color: darkgrey" th:replace="_fragment::footer">
        © 2024 Powered by Derek
    </div>
</body>
</html>
<!-- 请勿在项目正式环境中引用该 layui.js 地址 -->
<div th:replace="_include::tag-input">
    <script src="../static/layui/layui.js"></script>
    <script src="../static/jquery/jquery-3.7.1.min.js"></script>
    <script type="text/javascript" charset="utf8" src="../static/extend/version.js"></script>
    <script type="text/javascript" charset="utf8" src="../static/extend/inputTags.js"></script>
</div>
<!--layui模板引擎-->
<script id="imageTemplate" type="text/html">
    {{#  layui.each(d.list, function(index, item){ }}
    <div style="display: flex;">
        <div class="myui-upload-image-container" style="position: relative">
            <div class="myui-upload-image-delete-btn"  onclick="deleteImage({{index}})">
                <i class="layui-icon layui-icon-delete" style="font-size: 18px;"></i>
            </div>
            <img style="width: 105%;height: 105%" src="{{item}}">
        </div>
    </div>
    {{#  }); }}
    {{#  if(d.list.length === 0){ }}
    {{#  } }}
</script>

<script id="tagTemplate" type="text/html">
    {{#  layui.each(d.list, function(index, item){ }}
    <span id="tag-{{index}}"><em>{{item}}</em><button type="button" class="close" onclick="deleteTag({{index}})">×</button></span>
    {{#  }); }}
    {{#  if(d.list.length === 0){ }}
    {{#  } }}
</script>

<script id="tagSelectTemplate" type="text/html">
    {{#  layui.each(d.list, function(index, item){ }}
    <div class="myui-font-color-gray myui-tag-option" onclick="addTag('{{item.name}}')">
        <span>{{item.name}}</span>
        <div style="position: absolute;right: 20px">热度&nbsp;<span>{{item.quotedTimes}}</span></div>
    </div>
    {{#  }); }}
    {{#  if(d.list.length === 0){ }}
    {{#  } }}
</script>

<script th:inline="javascript">
    String.prototype.myTrim = function() {
        return this.replace(/^\s+|\s+$/g, '');
    };
    let imageList = { //数据
        "list":[]
    }
    let tagList = {
        'list': []
    }
    let tagSelectList = {
        'list': []
    }
    let laytpl = layui.laytpl;
    // 图片列表引擎
    let getTpl = imageTemplate.innerHTML, view = document.getElementById('view-div');
    laytpl(getTpl).render(imageList, function(html){view.innerHTML = html;});
    // 标签显示引擎
    let getTplTag = tagTemplate.innerHTML, viewTag = document.getElementById('tag-div');
    laytpl(getTplTag).render(tagList, function(html){viewTag.innerHTML = html;});
    // 推荐标签显示引擎
    let getTplTagSelect = tagSelectTemplate.innerHTML, viewTagSelect = document.getElementById('tag-select-div');
    laytpl(getTplTagSelect).render(tagSelectList, function(html){viewTagSelect.innerHTML = html;});

    // 为textarea添加input事件监听器
    $('#input-text').on('input propertychange', function() {
        // 当textarea内容发生变化时，这里的代码会被执行
        $('#words-number').text($('#input-text').val().length);
    });

    let imageUpload = false;
    $('#upload-container').hide();

    let selectTopicId = '';
    function selectTopic(index) {
        let div = $('#topics-container');
        let children = div.children();
        children.each(function() {
            $(this).removeClass('active')
        });
        $('#topic-' + index).addClass('active')
        selectTopicId = index;
    }

    function selectImage() {
        $('#file-input').click()
    }

    function deleteImage(i) {
        layer.confirm('是否删除该图片', {
            btn: ['确定', '取消'] //可以无限个按钮
        }, function(index, layero){
            imageList.list.splice(i, 1)
            laytpl(getTpl).render(imageList, function(html){view.innerHTML = html;});
            layer.close(index);
        }, function(index){});
    }

    $(document).ready(function() {
        // 当文件输入元素的值发生变化时触发
        $('#file-input').on('change', function() {
            // 获取选中的文件列表
            let files = this.files;
            if (imageList.list.length >= 10 || files.length > 10) {
                layer.open({
                    title: '系统提示'
                    ,content: '最多可以同时上传10张图片！'
                });
                return;
            }
            // 检查是否有文件被选中
            if (files.length > 0) {
                let loading = layer.msg('正在上传', {icon: 16, shade: 0.3, time: 0});
                for (let i = 0; i < files.length; i++) {
                    let file = files[i];
                    // 获取文件大小（以字节为单位）
                    let fileSize = file.size;
                    if (fileSize > 1024 * 1024 * 5) {
                        layer.open({
                            title: '系统提示'
                            ,content: '图片最大为5MB！'
                        });
                        return;
                    }
                    // 上传图片
                    let formData = new FormData();
                    formData.append('image', file);
                    formData.append('name', file.name);
                    formData.append('userId', [[${user.id}]])
                    $.ajax({
                        url: '/image/upload', // 上传到服务器的 URL
                        type: 'POST',
                        data: formData,
                        contentType: false, // 不设置内容类型，让浏览器自动处理
                        processData: false, // 不处理发送的数据，因为 FormData 已经处理了
                        success: function(res) {
                            // 请求成功时的回调函数
                            if (res.code !== 200) {
                                layer.open({
                                    title: '上传失败'
                                    ,content: res.msg
                                });
                            }
                            else {
                                imageList.list.push(res.data)
                                laytpl(getTpl).render(imageList, function(html){view.innerHTML = html;});
                            }
                        },
                        error: function(jqXHR, textStatus, errorThrown) {
                            // 请求失败时的回调函数
                            console.error('Error:', textStatus, errorThrown);
                        }
                    });
                }
                layer.close(loading);
            } else {
                // 没有文件被选中
                console.log('没有文件被选中');
            }
        });

        $('#image-button').on('click', function () {
            imageUpload = !imageUpload;
            if (imageUpload) {
                $('#upload-container').css('display', 'flex');
            } else {
                $('#upload-container').hide();
            }
        })

        $('#tag-input').on('keydown', function (e) {
            if (e.keyCode  === 13 || e.which === 13) {
                let val = e.target.value.myTrim()
                if (val.length > 10) {
                    layer.open({
                        title: '系统提示'
                        ,content: '标签最长10个字'
                    });
                    return;
                }
                if (val === '' ) {
                    return;
                }
                if(tagList["list"].length >= 5) {
                    layer.open({
                        title: '系统提示'
                        ,content: '最多支持5个标签'
                    });
                    return;
                }
                if (!tagList['list'].includes(val)) {
                    tagList['list'].push(val)
                    laytpl(getTplTag).render(tagList, function(html){viewTag.innerHTML = html;});
                }
                $('#tag-input').val('')
            } else if(e.keyCode === 8 || e.which === 8) {
                if ($('#tag-input').val() === '' && tagList['list'].length > 0) {
                    tagList['list'].pop()
                    laytpl(getTplTag).render(tagList, function(html){viewTag.innerHTML = html;});
                }
            }
        })

        $('#tag-input').on('input', function (e) {
            getRecommendTags();
        })

        $('#tag-input').on('focus', function () {
            getRecommendTags();
            $('#tag-select').addClass('active')
        })
        let selectHover = false;
        $("#tag-select").hover(
            function(){selectHover = true;},
            function(){selectHover = false;});
        $('#tag-input').on('focusout', function () {
            if (!selectHover) {
                $('#tag-select').removeClass('active')
            }
        })

        $('#post-btn').on('click',function () {
            if (selectTopicId === '') {
                layer.open({
                    title: '系统提示！'
                    ,content: '请选择话题'
                });
                return
            }
            let loading = layer.msg('正在发布', {icon: 16, shade: 0.3, time: 0});
            $.post('/dynamic/post',
                {
                    topicId: selectTopicId,
                    type: 0,
                    dynamic: $('#input-text').val(),
                    tags: JSON.stringify(tagList.list),
                    imageList: JSON.stringify(imageList.list)
                },
                function(res) {
                    layer.close(loading);
                    if (res.code !== 200) {
                        layer.open({
                            title: '系统提示'
                            ,content: res.msg
                        });
                    }
                    else {
                        $('#input-text').val('')
                        layer.alert('发布成功！', {
                            time: 3*1000,
                            success: function(layero, index){
                                let timeNum = this.time/1000, setText = function(start){
                                    layer.title('<span class="layui-font-red">'+ (start ? timeNum : --timeNum) + '</span> 秒后自动跳转', index);
                                };
                                setText(!0);
                                this.timer = setInterval(setText, 1000);
                                if(timeNum <= 0){
                                    clearInterval(this.timer);
                                    window.location.href = "/dynamic/" + res.data.id
                                }
                            },
                            end: function(){
                                clearInterval(this.timer);
                                window.location.href = "/dynamic/" + res.data.id
                            }
                        });
                    }
                });
        })
    });

    function addTag(tag) {
        if(tagList["list"].length >= 5) {
            layer.open({
                title: '系统提示'
                ,content: '最多支持5个标签'
            });
            return;
        }
        if (!tagList['list'].includes(tag)) {
            tagList['list'].push(tag)
            laytpl(getTplTag).render(tagList, function(html){viewTag.innerHTML = html;});
            $('#tag-input').val('')
            $('#tag-select').removeClass('active')
        }
    }

    function deleteTag(index) {
        $('#tag-' + index).remove();
        tagList['list'].splice(index, 1);
    }

    function getRecommendTags() {
        $.get('/tag/recommend?key=' + $('#tag-input').val(), function(res) {
            if (res.code === 200) {
                tagSelectList.list = res.data
                laytpl(getTplTagSelect).render(tagSelectList, function(html){viewTagSelect.innerHTML = html;});
            }
        });
    }
</script>